import React from 'react'
import PropTypes from 'prop-types'

export default class Counter extends React.Component {
  constructor (props) {
    super(props)
    this.increment = this.increment.bind(this)
    this.decrement = this.decrement.bind(this)
    this.state = {
      count: props.initValue
    }
  }

  increment () {
    this.updateCount(true)
  }

  decrement () {
    this.updateCount(false)
  }

  updateCount (flag) {
    const perVal = this.state.count
    const newVal = flag ? perVal + 1 : perVal - 1
    this.setState({count: newVal})
    this.props.onUpdate(newVal, perVal)
  }

  render () {
    const {caption} = this.props
    return (
      <div>
        <button style={{margin: '10px'}} onClick={this.increment}>+</button>
        <button style={{margin: '10px'}} onClick={this.decrement}>-</button>
        <span>{caption} count:{this.state.count}</span>
      </div>
    )
  }

}

Counter.propTypes = {
  caption: PropTypes.string.isRequired,
  initValue: PropTypes.number,
  onUpdate: PropTypes.func
}

Counter.defaultProps = {
  initValue: 0,
  onUpdate: f => f //什么都不做的函数
}
